package demo.controller;

import demo.pojo.User;
import demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService us;

    @GetMapping("/findAll")
    public String findAll(Model model) throws ParseException {
        List<User> user = us.findAll();
        model.addAttribute("user",user);
        return "user";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
         us.deleteUserById(id);
         return "redirect:/findAll";
    }

    @GetMapping("/findUserById/{id}")
    public String toEdit(@PathVariable Integer id, Model model) {
        model.addAttribute("user", us.findUserById(id));
        return "edit";
    }

    @PostMapping("/add")
    public String add(@RequestParam("name") String name, @RequestParam("birthday") Date birthday){
        User user = new User();
        user.setName(name);
        user.setBirthday(birthday);
        us.add(user);
        return "redirect:/findAll";
    }

    @PostMapping("/edit")
    public String edit(@RequestParam("id") Integer id,@RequestParam("name") String name, @RequestParam("birthday") Date birthday){
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setBirthday(birthday);
        us.edit(user);
        return "redirect:/findAll";
    }

    @GetMapping("/toadd")
    public String toadd(){
        return "add";
    }
}
